<template>
	<view>
		<up-navbar :title="$t('menu.trade')" :fixed="false">
			<template #left>
				<view></view>
			</template>
			<template #right>
				<view style="font-weight: 600;" @click="goPage('/pages/trade/trust')">{{$t("robot.my")}}</view>
			</template>
		</up-navbar>
		
		<view class="title-box" @click="show = true">
			{{pairsObj.currencyCode}}
			<image src="../../static/img/my/s.png" style="width: 20rpx; height: 12rpx;margin-left: 10rpx;"></image>
		</view>

		<view class="g2-box">
			<view class="tags">
				<view class="items">
					<text :class="period == item.value ? 'active' : ''" v-for="item in periodList" @click="handlePeriod(item)">{{item.label}}</text>
					<!-- <text>
						更多
					</text> -->
				</view>
				<!-- <view class="hide-box">
					隐藏
					<u-icon name="arrow-up" size="14px"></u-icon>
				</view> -->
			</view>
			<view class="charge-box">
				<qiun-data-charts type="candle" :opts="opts" :chartData="chartData" :disableScroll="true" :ontouch="true"
					:onzoom="true" />
			</view>
		</view>

		<view class="data-box">
			<view class="left-box">
				<view class="buy-box">
					<text @click="entrustType = 'buy'">{{$t('trade.buy')}}</text>
					<text @click="entrustType = 'sell'">{{$t('trade.sell')}}</text>
				</view>

				<view class="form-box1">
					<view class="form-item1">
						{{$t('trade.limitOrder')}}
						<image src="../../static/img/my/s.png" style="width: 20rpx; height: 12rpx;margin-left: 10rpx;"></image>
					</view>
					<image src="../../static/img/bot/i.png" style="width: 30rpx; height: 30rpx;margin-left: 10rpx;"></image>
				</view>

				<view class="form-box2">
					<view class="label-box">
						{{$t('trade.price')}}(USDC)
					</view>
					<view class="price-box">
						 <up-input :placeholder="$t('trade.placeholder1')" border="none" v-model="price" type="decimal"></up-input>
					</view>
				</view>

				<view class="main-title-box">
					<!-- 估值￥42.91 -->
				</view>

				<view class="form-box3">
					<up-input :placeholder="$t('trade.placeholder2')" border="none" v-model="num" type="decimal">
						<template #suffix>
							<text>WNA</text>
						</template>
					</up-input>
				</view>

				<view class="form-box4">
					<!-- <up-slider v-model="slideValue" showValue></up-slider> -->
					<!-- <up-steps current="1" dot>
						<up-steps-item title="0%"></up-steps-item>
						<up-steps-item title="25%"></up-steps-item>
						<up-steps-item title="50%"></up-steps-item>
						<up-steps-item title="75%"></up-steps-item>
						<up-steps-item title="100%"></up-steps-item>
					</up-steps> -->
				</view>

				<!-- <view class="form-box3">
					<up-input :placeholder="$t('trade.placeholder3')" border="none" v-model="tradeAmount" type="number">
						<template #suffix>
							<text>USDC</text>
						</template>
					</up-input>
				</view> -->

				<view class="usable-box">
					<view class="number-box">
						<text>{{$t('trade.available')}} <text>{{Number(balance.availableBalance).toFixed(6)}} USDC</text></text><br />
						<text>{{$t('trade.available')}} <text>{{Number(columns[0].find(item => item.currencyCode == 'WNA').availableBalance).toFixed(6)}} WNA</text></text>
					</view>
					<!-- <image src="/static/img/bot/switch-icon.png" style="width: 24rpx; height: 24rpx;"></image> -->
				</view>

				<view class="btn-box">
					<u-button v-if="entrustType == 'buy'" type="primary" shape="circle" color="#44b672" @click="submit('BUY')">{{$t('trade.buy')}}WNA</u-button>
					<u-button v-if="entrustType == 'sell'" type="error" shape="circle" @click="submit('SELL')">{{$t('trade.sell')}}WNA</u-button>
				</view>

			</view>
			<view class="right-box">
				<view class="table-tr-box">
					<view class="item">
						{{$t('trade.price')}}
						<text>USDC</text>
					</view>
					<view class="item">
						{{$t('robot.num')}}
						<text>(WNA)</text>
					</view>
				</view>
				<view class="table-td-box" v-for="item in tradeDex.sell" @click="buyClick(item)">
					<view class="item">
						{{item.price}}
					</view>
					<view class="item">
						{{item.surplusNum}}
					</view>
				</view>

				<view class="table-td-box">
					<view class="item" style="font-size: 32rpx;color: #ec6d6e; margin-bottom: 20rpx;">
						{{tradeDex.price}}
					</view>
				</view>

				<view class="table-td-box" v-for="item in tradeDex.buy" @click="buyClick(item)">
					<view class="item" style="color: #44b672;">
						{{item.price}}
					</view>
					<view class="item">
						{{item.surplusNum}}
					</view>
				</view>

				<!-- <view class="form-number-box">
					0.01
					<image src="../../static/img/my/s.png" style="width: 20rpx; height: 12rpx;margin-left: 10rpx;"></image>
				</view> -->
			</view>
		</view>

		<up-gap height="10" bgColor="#f5f5f5"></up-gap>

		<!-- <view class="group-box">
			<view>
				<view class="item action">
					<text>{{$t('trade.commission')}}</text>
					<image src="../../static/img/my/s.png" style="width: 18rpx; height: 12rpx;margin-left: 10rpx;"></image>
				</view>
				<view class="item">
					<text>{{$t('trade.currency')}}</text>
				</view>
				<view class="item">
					<text>{{$t('trade.property')}}</text>
				</view>
			</view>
			<view @click="goPage('/pages/trade/trust')">
				<image src="../../static/img/bot/time.png" style="width: 30rpx; height: 30rpx;"></image>
			</view>
		</view>
		<view style="width: calc(100vw - 80rpx);margin:0 auto;"><up-gap height="1" bgColor="#f5f5f5"></up-gap></view>
		<view class="mul-cancel">
			<view>
				<up-checkbox-group v-model="selectCancel" placement="column" @change="checkboxChange">
					<up-checkbox :label="$t('trade.breed')" :name="1">
					</up-checkbox>
				</up-checkbox-group>
			</view>
			<view class="btn-box">
				{{$t('trade.batch')}}
			</view>
		</view> -->
		<view style="width: calc(100vw - 80rpx);margin:0 auto;"><up-gap height="1" bgColor="#f5f5f5"></up-gap></view>
		
		<!-- <view class="order-item">
			<view class="order-title-box">
				WNA/USDC
				<view class="btn-box">
					撤单
				</view>
			</view>
			<view class="tags">
				<text>限时</text>
				<text>卖出</text>
				04/06 15:49
			</view>
			
			<view class="table-box">
				<view class="table-tr">
					<text>委托数量 (WNA)</text>
					<text>已成交量 (WNA)</text>
					<text>委托价格</text>
				</view>
				<view class="table-td">
					<text>669.13</text>
					<text>0</text>
					<text>11</text>
				</view>
			</view>
		</view> -->
		
		<up-picker :show="show" :columns="pairsColumns" keyName="currencyCode" closeOnClickOverlay @close="show = false" @cancel="show = false" @confirm="confirm"></up-picker>
		<view class="bottom-box"></view>
		<tabbarVue :current="3"></tabbarVue>
	</view>
</template>

<script setup>
	import tabbarVue from '@/components/tabbar/index.vue'
	import uCharts from '@qiun/ucharts'
	import {
		onLoad,
		onShow,
		onReady,
		onHide
	} from '@dcloudio/uni-app'
	import {
		ref
	} from 'vue'
	import {
		getKline,
		getCurrencyBalance,
		getQueryOrder,
		postCreateOrder,
		queryTradeDex,
		getPairs
	} from '@/common/api/common.js'
	import { timeFormat } from '@/uni_modules/uview-plus';
	import { useI18n } from 'vue-i18n';
	const {t} = useI18n();

	const chartData = ref({})
	const selectCancel = ref([])
	const periodList = ref([
		{label: t('trade.m1'), value: '1m'},
		{label: t('trade.m5'), value: '5m'},
		{label: t('trade.m15'), value: '15m'},
		{label: t('trade.m30'), value: '30m'},
		{label: t('trade.h1'), value: '1h'},
		{label: t('trade.d1'), value: '1d'},
		{label: t('trade.w1'), value: '1w'},
	])
	const show = ref(false);
	const columns = ref([[]]);
	const pairsColumns = ref([[]]);
	const pairsObj = ref({})
	const balance = ref({})
	const entrustType = ref('buy')
	const tradeDex = ref({});
	const price = ref('')
	const num = ref('')
	const tradeAmount = ref('')
	const slideValue = ref(0)
	
	const period = ref('1m')
	const opts = ref({
		rotate: false,
		rotateLock: false,
		color: ["#1890FF", "#91CB74", "#FAC858", "#EE6666", "#73C0DE", "#3CA272", "#FC8452", "#9A60B4", "#ea7ccc"],
		padding: [15, 15, 0, 15],
		dataLabel: false,
		enableScroll: true,
		enableMarkLine: true,
		legend: {},
		xAxis: {
			labelCount: 4,
			itemCount: 40,
			disableGrid: true,
			gridColor: "#CCCCCC",
			gridType: "solid",
			dashLength: 4,
			scrollShow: true,
			scrollAlign: "left",
			scrollColor: "#A6A6A6",
			scrollBackgroundColor: "#EFEBEF"
		},
		yAxis: {
			data: []
		},
		extra: {
			candle: {
				color: {
					upLine: "#f04864",
					upFill: "#f04864",
					downLine: "#2fc25b",
					downFill: "#2fc25b"
				},
				average: {
					show: true,
					name: [
						"MA5",
						"MA10",
						"MA30"
					],
					day: [
						5,
						10,
						20
					],
					color: [
						"#1890ff",
						"#2fc25b",
						"#facc14"
					]
				}
			},
			markLine: {
				type: "dash",
				dashLength: 5,
				data: [{
						value: 2150,
						lineColor: "#f04864",
						showLabel: true
					},
					{
						value: 2350,
						lineColor: "#f04864",
						showLabel: true
					}
				]
			},
			tooltip: {
				showCategory: true
			}
		},
	})
	
	
	
	const timerId = ref('')

	const getServerData = (data) => {
		//模拟从服务器获取数据时的延时
		setTimeout(() => {
			//模拟服务器返回数据，如果数据格式和标准格式不同，需自行按下面的格式拼接
			let time = data.map(item => timeFormat(item.time,'mm/dd hh:MM'))
			let series = data.map(item => {
				let arr = [item.open,item.close,item.low,item.high]
				return arr
			})
			// let yMax = Math.max(...series);
			// let yMin = Math.min(...series);
			// opts.value.yAxis.data[0].min = yMin - 6;
			// opts.value.yAxis.data[0].max = yMax + 10;
			let res = {
				categories: time.length > 0 ? time: [],
				series: [{
					name: "上证指数",
					data: series.length > 0 ? series : []
				}]
			};
			chartData.value = JSON.parse(JSON.stringify(res));
		}, 500);
	}

	const checkboxChange = e => {
		selectCancel.value = e
	}
	
	const handlePeriod = e => {
		period.value = e.value
		getKlineFn()
	}
	
	const getKlineFn = async () => {
		const res = await getKline({
			period: period.value,
			page: 0,
			pageSize: 200
		})
		if (res.status == 0) {
			getServerData(res.result)
		} else {
			// uni.$u.toast(res.errorMessage)
		}
	}
	
	const getCurrencyBalanceFn = async () => {
		const res = await getCurrencyBalance({
			marketId: 1
		})
		if(res.status == 0){
			res.result.memberAccount.map((item,index) => {
				item.id = index + 1
			})
			balance.value = res.result.memberAccount[0]
			columns.value[0] = res.result.memberAccount
		}
	}
	
	
	const getPairsFn = async () => {
		const res = await getPairs({id: '',page: 0,pageSize: 10})
		if(res.status == 0){
			res.result.content.map((item,index) => {
				item.id = index + 1
			})
			pairsObj.value = res.result.content[0]
			pairsColumns.value[0] = res.result.content
		}
	}
	
	const getQueryOrderFn = async () => {
		const buy = await queryTradeDex()
		if(buy.status == 0){
			tradeDex.value = buy.result
		}
	}
	
	const confirm = (e) => {
	  // balance.value = e.value[0]
	  show.value = false;
	  if(e.value[0].currencyCode == 'XTTA/USDC') {
		  uni.$u.toast(t('notYetOpen'))
		  return
	  }
	  pairsObj.value = e.value[0]
	  
	};
	
	const buyClick = (item) => {
	  price.value = item.price
	  // num.value = item.num
	};
	
	const submit = async (type) => {
		if(!price.value) {
			uni.$u.toast(t('trade.placeholder1'))
			return
		}
		if(!num.value) {
			uni.$u.toast(t('trade.placeholder2'))
			return
		}
		// if(!tradeAmount.value) {
		// 	uni.$u.toast(t('trade.placeholder3'))
		// 	return
		// }
		uni.showModal({
			title: '提示',
			content: type == 'BUY' ? '确认要进行买入吗？' : '确认要进行卖出吗？',
			success: function (res) {
				if (res.confirm) {
					// console.log('用户点击确定');
					postCreateOrder({
						pairId: '1',
						num: num.value,
						// tradeAmount: tradeAmount.value,
						tradeAmount: '',
						price: price.value,
						entrustType: type,
						priceType: 'CUSTOM_PRICE'
					}).then(data => {
						if(data.status == 0){
							getQueryOrderFn();
							getCurrencyBalanceFn();
							uni.$u.toast(t('success'))
							num.value = ''
						}
					})
				} else if (res.cancel) {
					// console.log('用户点击取消');
				}
			}
		});
	}
	
	const goPage = url => {
		clearInterval(timerId.value);
		uni.navigateTo({
			url: url
		})
	}
	
	const init = () => {
		timerId.value = setInterval(()=>{
			getCurrencyBalanceFn()
			getQueryOrderFn()
			getPairsFn()
		},1000)
	}

	onHide(()=>{
		clearInterval(timerId.value);
	})
	
	onShow(() => {
		init()
	})

	onReady(() => {
		getKlineFn()
		// setInterval(() => {
		// 	getKlineFn()
		// },3000)
	})
</script>

<style lang="scss" scoped>
	.title-box {
		padding: 20rpx 40rpx 0;
		font-weight: bold;
		font-size: 36rpx;
		color: #1F1F1F;
		display: flex;
		justify-content: flex-start;
		align-items: center;
	}

	.g2-box {
		.tags {
			padding: 30rpx 40rpx 20rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
			font-weight: 500;
			font-size: 24rpx;
			color: #1F1F1F;

			.items {
				text {
					padding-right: 16rpx;
				}
				.active {
					color: rgb(68, 182, 114);
				}
			}

			.hide-box {
				display: flex;
				justify-content: flex-end;
				align-items: center;
			}
		}

		.charts-box {
			width: 100%;
			height: 300px;
		}
	}

	.data-box {
		padding: 30rpx 40rpx;
		display: flex;
		justify-content: space-between;

		.left-box {
			width: calc(100% - 140rpx - 40rpx);
			padding-right: 40rpx;

			.buy-box {
				width: 383rpx;
				height: 60rpx;
				background-image: url('../../static/img/bot/buy-btn-bg.png');
				background-size: 100% 100%;
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 20rpx;

				text {
					width: 50%;
					text-align: center;
					color: #ffffff;
				}
			}

			.form-box1 {
				display: flex;
				justify-content: space-between;
				align-items: center;

				.form-item1 {
					width: calc(100% - 40rpx - 10rpx);
					height: 60rpx;
					border: 1px solid #1F1F1F20;
					background-color: #f5f5f5;
					display: flex;
					justify-content: space-between;
					align-items: center;
					padding: 0 20rpx;
					box-sizing: border-box;
					font-size: 24rpx;
					border-radius: 4rpx;
				}
			}

			.form-box2 {
				width: 100%;
				border: 1px solid #1F1F1F20;
				background-color: #f5f5f5;
				padding: 10rpx 20rpx;
				box-sizing: border-box;
				font-size: 24rpx;
				margin-top: 10rpx;
				border-radius: 4rpx;

				.label-box {
					font-size: 24rpx;
					color: #1F1F1F90;
				}

				.price-box {
					font-size: 28rpx;
				}
			}

			.main-title-box {
				font-size: 28rpx;
				padding: 18rpx 0;
			}

			.form-box3 {
				width: 100%;
				border: 1px solid #1F1F1F20;
				background-color: #f5f5f5;
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 15rpx 20rpx;
				box-sizing: border-box;
				font-size: 24rpx;
				border-radius: 4rpx;
				color: #1F1F1F80;
			}

			.form-box4 {
				padding: 18rpx 0;

				::v-deep .u-steps-item__wrapper {
					background: none;
				}

				::v-deep .u-text__value--content {
					font-size: 20rpx !important;
					line-height: 20rpx !important;
				}

				::v-deep .u-text__value--main {
					font-size: 20rpx !important;
					line-height: 20rpx !important;
				}

				::v-deep .u-steps-item__wrapper__dot {
					width: 10rpx;
					height: 10rpx;
					background-color: #1F1F1F !important;
					border: 6rpx solid #ccc !important;
				}
			}

			.usable-box {
				display: flex;
				justify-content: space-between;
				margin-top: 18rpx;

				.number-box {
					font-size: 24rpx;
					color: #1F1F1F80;

					text {
						text {
							color: #1F1F1F;
						}
					}
				}
			}

			.btn-box {
				margin-top: 30rpx;
			}

		}

		.right-box {
			.table-tr-box {
				font-size: 24rpx;
				color: #1F1F1F90;
				display: flex;
				justify-content: space-between;
				align-items: center;

				.item {
					text {
						font-weight: 300;
					}
				}

				.item:last-child {
					text-align: right;
				}
			}

			.table-td-box {
				font-size: 24rpx;
				color: #1F1F1F90;
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 6rpx 0;

				.item {
					color: #ec6d6e;

					text {
						font-weight: 300;
					}
				}

				.item:last-child {
					color: #1F1F1F90;
				}
			}

			.form-number-box {
				width: 100%;
				height: 60rpx;
				border: 1px solid #1F1F1F20;
				background-color: #f5f5f5;
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 0 20rpx;
				box-sizing: border-box;
				font-size: 24rpx;
				border-radius: 4rpx;
				margin-top: 10rpx;
			}
		}
	}

	.group-box {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx 40rpx;

		view:first-child {
			display: flex;
			justify-content: flex-start;
			align-items: center;

			.item {
				margin-right: 30rpx;
				color: #999;
			}

			.action {
				color: #1F1F1F;
			}
		}
	}

	.mul-cancel {
		padding: 20rpx 40rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;

		.btn-box {
			padding: 8rpx 30rpx;
			background: #f5f5f5;
			border-radius: 30rpx;
		}
	}
	
	.order-item{
		width: calc(100% - 80rpx);
		margin: 20rpx auto 0;
		.order-title-box{
			font-weight: 500;
			font-size: 30rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
			
			.btn-box {
				font-weight: 450;
				padding: 8rpx 30rpx;
				background: #f5f5f5;
				border-radius: 30rpx;
			}
		}
		.tags{
			margin: 10rpx 0 0;
			color: #1F1F1F80;
			text{
				padding: 8rpx 10rpx;
				border-radius: 8rpx;
				background: #f8e9ec;
				color: #c3426d;
				margin-right: 10rpx;
			}
		}
		
		.table-box{
			margin-top: 20rpx;
			font-size: 26rpx;
			.table-tr{
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 10rpx 0;
				color: #1F1F1F80;
				text-align: left;
				text{
					width: 33.33%;
					display: block;
				}
				text:last-child{
					text-align: right;
				}
			}
			.table-td{
				display: flex;
				justify-content: space-between;
				align-items: center;
				text-align: left;
				text{
					width: 33.33%;
					display: block;
				}
				text:last-child{
					text-align: right;
				}
			}
		}
	}
</style>